package com.blog.service.service;

import com.blog.check.result.Result;
import com.blog.form.LoginForm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * 登录服务
 *
 * @author 泡面ing
 * @date 2021/11/17
 */
@Service
public class LoginService extends BaseService{

    public Result login(LoginForm loginForm, HttpServletRequest request){
        String userName = loginForm.getUsername();
        String password = DigestUtils.md5DigestAsHex(loginForm.getPassword().getBytes(StandardCharsets.UTF_8));
//        从shiro中获取subject,得到一个主题对象，subject代表了当前的user用户，
        Subject subject = SecurityUtils.getSubject();
//        用户名密码令牌
        UsernamePasswordToken token =new UsernamePasswordToken(userName,password);

        try{
//            执行登录认证请求->传递令牌到realm中
            subject.login(token);
            return Result.success();
        }catch (AuthenticationException e){
            e.printStackTrace();
            request.setAttribute("err Info","用户名密码或错误");
            return Result.failure("用户名密码或错误");
        }
    }

    public Result logout(){

        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
            return Result.success();
        }else {
            return Result.failure("logoutFalse");
        }

    }
}
